let size = 0;
let canSwitch = true;
function init() {
  window.addEventListener("keyup", (e) => {
    if (e.key === "u") {
      e.preventDefault();
      switchImg("up");
    } else if (e.key === "n") {
      e.preventDefault();
      switchImg("down");
    }
  });
  window.electronAPI.onUpdate((value) => {
    if (size < 3) {
      const urls = [
        "../../cache/0.avif",
        value > 1 ? "../../cache/1.avif" : "../../cache/0.avif",
        value > 2 ? "../../cache/2.avif" : "../../cache/0.avif",
      ];
      const img1 = document.createElement("img");
      img1.setAttribute("src", urls[0]);
      const img2 = document.createElement("img");
      img2.setAttribute("src", urls[1]);
      const img3 = document.createElement("img");
      img3.setAttribute("src", urls[2]);
      document.body.innerHTML = "";
      document.body.appendChild(img1);
      document.body.appendChild(img2);
      document.body.appendChild(img3);
      img2.scrollIntoView({
        block: "start",
      });
    }
    size = value;
  });
}
init();
/**
 *
 * @param {'up'|'down'} direction
 * @param {number}} size
 */
function switchImg(direction) {
  if (!canSwitch) return;
  if (size <= 1) return;
  canSwitch = false;
  setTimeout(() => {
    canSwitch = true;
  }, 1000);
  if (direction === "up") {
    const imgs = document.getElementsByTagName("img");
    const temp = imgs[2].getAttribute("src");
    imgs[2].setAttribute("src", imgs[1].getAttribute("src"));
    imgs[1].setAttribute("src", imgs[0].getAttribute("src"));
    imgs[2].scrollIntoView({
      block: "start",
    });
    if (size <= 3) {
      imgs[0].setAttribute("src", temp);
    } else {
      const paths = temp.split("/");
      imgs[0] =
        "../../cache/" +
        window.electronAPI.getNewImage(paths[paths.length - 1]);
    }
    imgs[1].scrollIntoView({
      behavior: "smooth",
      block: "start",
    });
  } else if (direction === "down") {
    const imgs = document.getElementsByTagName("img");
    const temp = imgs[0].getAttribute("src");
    imgs[0].setAttribute("src", imgs[1].getAttribute("src"));
    imgs[1].setAttribute("src", imgs[2].getAttribute("src"));
    imgs[0].scrollIntoView({
      block: "start",
    });
    imgs[1].scrollIntoView({
      behavior: "smooth",
      block: "start",
    });
    if (size <= 3) {
      imgs[2].setAttribute("src", temp);
    } else {
      const paths = temp.split("/");
      imgs[2] =
        "../../cache/" +
        window.electronAPI.getNewImage(paths[paths.length - 1]);
    }
  }
}
